<?php

/**
 * @file
 * A php library for interacting with eve
 *
 * @copyright 2010 David Hinkle
 * @author David Hinkle
 * @license GPL
 */

require_once("config.php");

/**
 * This class manages the eve browser api
 */
class eveBrowser
{
	public $pilotName;
	public $allianceName;
	public $corpName;
	public $trusted;
	public $claimsUrl;
	
	function __construct($urlIn)
	{
		$this->claimsUrl = $urlIn;
	}

	/*
	 * Attempt to gain trust from the client.
	 * May cause a page reload.
	 */
	function getTrust()
	{
		$browser = $_SERVER['HTTP_USER_AGENT'];
		if (strstr($browser, "EVE-IGB") === false)
			$ingame = false;
		else
			$ingame = true;

		if ($ingame)
		{
			// check for trust
			if ($_SERVER['HTTP_EVE_TRUSTED']=='No')
			{
				?>
					<body bgcolor="black">
						<script type="text/javascript">
							CCPEVE.requestTrust('<? echo $this->claimsUrl; ?>');
						</script>
						<center>
							<button type="button" onclick="window.location.reload()">Trust me (<? echo $this->claimsUrl; ?>) and then click here</button>
						</center>
				<?
				exit;
			}
			else
			{
				$this->trusted = true;
				$this->pilotName = $_SERVER['HTTP_EVE_CHARNAME'];

				if (isset($_SERVER['HTTP_EVE_ALLIANCENAME']))
					$this->allianceName = $_SERVER['HTTP_EVE_ALLIANCENAME'];
				else
					$this->allianceName = "None";

				$this->corpName = $_SERVER['HTTP_EVE_CORPNAME'];
			}
		}
	}

}


/**
 * Handles communication with killboard
 */
class killboard
{
	private $url;
	private $conn;

	private $insideItem = false;
	private $tag;
	private $title, $description, $guid, $pubDate, $apiId;
	private $victim, $corp, $ship, $system, $killer, $killerAlliance;

	private $parsed;
	private $debug = false;
	private $message;

	function getMessage() { return $this->message; }

	function __construct($connIn, $urlIn)
	{
		$this->url = $urlIn;
		$this->conn = $connIn;
	}

	// output helper function
	function dump($dump)
	{
		if (!$this->debug) return;

		echo($dump);
   	flush();
	}

	// automatic parse function called on first visit to index.php
	function parse()
	{
		$this->parsed = 0;

		// Create an XML parser
		$xml_parser = xml_parser_create();

		// Set the functions to handle opening and closing tags
		xml_set_element_handler($xml_parser,
															array($this, "startElement"),
															array($this, "endElement"));

		// Set the function to handle blocks of character data
		xml_set_character_data_handler($xml_parser, array($this, "characterData"));

		// Determine the next killid
		$res = mysql_query("select max(killId) as killId from losses");
   	$row = mysql_fetch_assoc($res);

   	if (isset($row['killId']))
   		$append = "&lastkllid=".($row['killId']+1);
   	else
   		$append = "&lastkllid=99500";

   	mysql_free_result($res);

   	$this->dump($this->url."/?a=feed&APILosses=true&corp=The+Graduates".$append."<br/>\n");

		// Open the XML file for reading
		$fp = fopen($this->url."/?a=feed&APIlosses=true&corp=The+Graduates".$append,"r")
       		or die("Error reading RSS data.");

		// Read the XML file 4KB at a time
		while ($data = fread($fp, 4096))
   		// Parse each 4KB chunk with the XML parser created above
   		xml_parse($xml_parser, $data, feof($fp))
       		// Handle errors in parsing
       		or die(sprintf("XML error: %s at line %d",
           		xml_error_string(xml_get_error_code($xml_parser)),
           		xml_get_current_line_number($xml_parser)));

		// Close the XML file
		fclose($fp);

		// Free up memory used by the XML parser
		xml_parser_free($xml_parser);

		return($this->parsed);
	}


	// search for missing killids
	function parse_player($player)
	{
		$this->parsed = 0;

		// Create an XML parser
		$xml_parser = xml_parser_create();

		// Set the functions to handle opening and closing tags
		xml_set_element_handler($xml_parser,
			array($this, "startElement"),
			array($this, "endElement"));

		// Set the function to handle blocks of character data
		xml_set_character_data_handler($xml_parser, array($this, "characterData"));

		// Determine the next killid
		$res = mysql_query("select max(killId) as killId from losses where victim = '".$player."'");
   	$row = mysql_fetch_assoc($res);

   	if (isset($row['killId']))
   		$append = "&lastkllid=".($row['killId']-2000);
		else
   		$append = "&lastkllid=135000";

		mysql_free_result($res);

   	$this->dump($this->url."/?a=feed&APIlosses=true&pilot=".$player.$append."<br>\n");

		// Open the XML file for reading
		$fp = fopen($this->url."/?a=feed&APIlosses=true&pilot=".$player.$append,"r")
       	or die("Error reading RSS data.");

		// Read the XML file 4KB at a time
		while ($data = fread($fp, 4096))
		{
			$this->dump('reading data...');
   		// Parse each 4KB chunk with the XML parser created above
   		xml_parse($xml_parser, $data, feof($fp))
      		// Handle errors in parsing
       		or die(sprintf("XML error: %s at line %d",
           		xml_error_string(xml_get_error_code($xml_parser)),
           		xml_get_current_line_number($xml_parser)));
    }

		// Close the XML file
		fclose($fp);
		$this->dump('closed XML file');

		// Free up memory used by the XML parser
		xml_parser_free($xml_parser);

		$this->dump('return: '.$this->parsed);
		if ($this->message == "") $this->message = "No missing kills found.<br/>";
		return(0);

	}

	function startElement($parser, $tagName, $attrs)
	{
		$this->dump("&lt;".$tagName." ".$this->insideItem."&gt;<br/>");

		if ($this->insideItem)
 		{
   		$this->tag = $tagName;
 		}
 		elseif ($tagName == "ITEM")
 		{
    	$this->insideItem = true;
 		}
	}

	function characterData($parser, $data)
	{
		$this->dump("\t".$data."<br/>");

 		if ($this->insideItem)
		{
			switch ($this->tag)
			{
				case "TITLE":
	     		$this->title .= $data;
	     		break;
	     	case "DESCRIPTION":
	     		$this->description .= $data;
	     		break;
	     	case "GUID":
	     		$this->guid .= $data;
	     		break;
	     	case "PUBDATE":
	     		$this->pubDate .= $data;
	     		break;
	     	case "APIID":
	     		$this->apiId .= $data;
	     		break;
	 		}
		}
	}

	function parseKillmail($km)
	{
		$lines = split("\n", $km);
		$inVictim = true;

		foreach ($lines as $line)
		{
			@list($field, $value) = split(":", $line);
			$field = trim($field);
			$value = trim($value);

			switch($field)
			{
				case "Victim":
					$this->victim = $value;
					break;
				case "Corp":
					if ($inVictim) $this->corp = $value;
					break;
				case "Destroyed":
					if ($inVictim) $this->ship = $value;
					break;
				case "System":
					$this->system = $value;
					break;
				case "Name":
					$this->killer = trim(str_replace("(laid the final blow)","", $value));
					break;
				case "Alliance":
					if (!$inVictim) $this->killerAlliance = $value;
					break;
				case "Involved parties":
					$inVictim = false;
					break;
				case "Damage Done":
					return;
			}
		}
	}

	function endElement($parser, $tagName)
	{
		$this->dump("&lt;/".$tagName."&gt;<br>/");

   	if ($tagName == "ITEM")
   	{
   		$this->url = trim($this->url);
   		$this->guid = trim($this->guid);
   		$this->title = trim($this->title);

   		$this->parseKillmail($this->description);

   		$res = mysql_query("select typeID from invTypes where typeName = '".$this->ship."'", $this->conn);
   		$row = mysql_fetch_assoc($res);
   		$shipId = $row['typeID'];
   		mysql_free_result($res);

   		$query = sprintf("insert into losses (killId, victim, corp, ship, shipId, system, killer, killerAlliance)
   				values (%s, '%s', '%s', '%s', %s, '%s', '%s', '%s')",
			    mysql_real_escape_string($this->title),
			    mysql_real_escape_string($this->victim),
			    mysql_real_escape_string($this->corp),
			    mysql_real_escape_string($this->ship),
			    mysql_real_escape_string($shipId),
			    mysql_real_escape_string($this->system),
			    mysql_real_escape_string($this->killer),
    			mysql_real_escape_string($this->killerAlliance));

			$query2 = sprintf("select killId from losses where killId = ".$this->title);
			$res = mysql_query($query2, $this->conn);

			if (!$res)
			{
				die('Invalid query: ' . mysql_error());
			}

			if (mysql_num_rows($res) == 0 && $this->corp === 'The Graduates')
			{
				mysql_query($query, $this->conn);
    		$this->message .= "Found missing kill: <a href=".$this->url."/?a=kill_detail&kll_id=".$this->title.">".$this->title."</a><br />";
			}
    	else
    	{
    		$this->dump("Found killid: ".$query2."<br />");
    	}

			$this->parsed++;

    	$this->title = $this->description = $this->guid = $this->pubDate = $this->apiId = "";
    	$this->victim = $this->corp = $this->ship = $this->system = $this->killer = $this->killerAlliance = "";

    	$this->insideItem = false;
   	}

	} // endElement


} // killboard

?>